<template>
  <div class="bonus">
    <dt-header :line-number="type == 'SPECIAL' ? 2 : 3" :title="title" :label-width="180" ref="header">
      <div v-if="name == 'billEdit' && info && info.status == 'UNSUBSTITUTED'" slot="title">
        <span
          @click="onEditTitle"
          style="cursor: pointer; color: #3366ff; text-decoration: underline; line-height: 30px">
          修改
        </span>
      </div>
      <div>
        <div v-if="(name == 'billApprovalDetail' || name == 'caseBillApprovalDetail') && auditId" class="btn">
          <Button type="primary" @click="onAudit">审核</Button>
        </div>
        <div v-else-if="name == 'billEdit' && type == 'SPECIAL'" class="btn">
          <Button type="primary" @click="onImport">数据导入</Button>
          <Button type="primary" @click="onClear">清空数据</Button>
          <Button type="primary" :disabled="!info" @click="onSubmit">全部提交</Button>
        </div>
        <div v-else-if="name == 'billEdit'" class="btn">
          <Button type="primary" v-if="type != 'YEAR_END'" :disabled="roomTotal <= 0" @click="onBatchUpdate">
            批量修改本次结算
          </Button>
          <Button
            type="primary"
            v-if="type != 'HANDOVER' && type != 'YEAR_END' && info && info.exceptionAttach"
            @click="onErrExport">
            异常房源导出
          </Button>
          <Button type="primary" @click="onExport">导出</Button>
          <Button type="primary" :disabled="!info" @click="onSubmit">提交</Button>
        </div>
        <div
          v-else-if="name == 'billDetail' || name == 'billApprovalDetail' || name == 'caseBillApprovalDetail'"
          class="btn">
          <Button type="primary" @click="onFlow">流程信息</Button>
          <Button type="primary" @click="onExport">导出</Button>
        </div>
      </div>
    </dt-header>

    <div v-if="type == 'PRE'" class="tip">
      ！预发奖金前需先设置标准奖金模板，无匹配标准奖金模板的房源不可预发
    </div>

    <Tabs v-if="type != 'YEAR_END'" type="card" :animated="false" @on-click="onTab">
      <TabPane v-if="type == 'SPECIAL'" label="房源奖金结算" name="room">
        <p class="title">特殊奖金调整</p>
        <dt-grid ref="room" page :onFetch="onFetchRoom" rowKey />
      </TabPane>
      <TabPane v-else label="房源奖金结算" name="room">
        <p v-if="agencyList.length > 0" class="title">代理费调整</p>
        <dt-grid v-show="agencyList.length > 0" ref="agency" height-resize :list="agencyList" />
        <p class="title">房源奖金明细</p>
        <dt-grid ref="room" page :onFetch="onFetchRoom" rowKey />
      </TabPane>
      <TabPane v-if="type == 'SPECIAL'" label="人员奖金汇总" name="person">
        <p class="title">人员调整</p>
        <dt-grid ref="person" :list="personList" />
      </TabPane>
      <TabPane v-else label="人员奖金汇总" name="person">
        <p class="title">人员调整</p>
        <dt-grid ref="person" :onFetch="onFetchPerson" />
      </TabPane>
      <TabPane label="奖金科目明细" name="detail">
        <dt-grid ref="detail" :onFetch="onFetchDetail" />
      </TabPane>
    </Tabs>

    <dt-grid v-else ref="person" :list="personList" :row-style="rowStyle" />

    <room-modal ref="roomModal" @update="update" />
    <reason-modal ref="reason" />
    <title-modal ref="title" />
    <submit-modal ref="submit" @update="update" />
    <audit-modal ref="audit" />
    <import-modal ref="import" @success="update" />
    <process-modal ref="process" />
    <year-modal ref="year" />
    <upload-modal ref="upload" @success="update" />
  </div>
</template>

<script>
  import RoomColumn from './opt/RoomColumn.js'
  import SpecialRoomColumn from './opt/SpecialRoomColumn.js'
  import PersonColumn from './opt/PersonColumn.js'
  import DetailColumn from './opt/DetailColumn.js'
  import AgencyColumn from './opt/AgencyColumn.js'
  import BillOpt from './opt/BillOpt.js'

  import billMgr from '@/biz/bonus/bill'
  import specialMgr from '@/biz/bonus/billSpecial'
  import yearMgr from '@/biz/bonus/billYear'
  import toolMgr from '@/biz/base/tool.js'

  import roomModal from './components/room-modal.vue'
  import reasonModal from './components/reason-modal.vue'
  import titleModal from './components/title-modal.vue'
  import submitModal from './components/submit-modal.vue'
  import importModal from './components/import-modal.vue'
  import yearModal from './components/year-modal.vue'
  import uploadModal from './components/upload-modal.vue'
  import auditModal from '@/components/biz/audit/audit-modal.vue'
  import processModal from '@/components/biz/audit/process-modal.vue'

  export default {
    components: {
      roomModal,
      reasonModal,
      titleModal,
      submitModal,
      importModal,
      auditModal,
      processModal,
      yearModal,
      uploadModal
    },
    data() {
      return {
        type: 'STANDARD',
        title: '',
        id: null,
        info: null,
        agencyList: [],
        name: null,
        auditId: null,
        personList: [],
        tabName: 'room',
        showError: true,
        roomTotal: 0
      }
    },
    mounted() {
      this.name = this.$route.name
      this.type = this.$route.query.type
      this.auditId = this.$route.query.auditId
      this.id = this.$route.query.id
      this.$nextTick(() => {
        this.init()
      })
    },
    methods: {
      rowStyle(e) {
        return {
          'background-color': e.row.isCanAdjust != false ? '#fff' : '#F2F2F2'
        }
      },
      init() {
        let update = () => {
          this.update()
        }
        let change = (item) => {
          let update = () => {
            if (item.adjustAmount == null) {
              item.adjustAmount = 0
            }
            if (this.type == 'YEAR_END') {
              yearMgr
                .personEdit(this.id, item.bonusDetailId, item.adjustAmount, item.adjustReason)
                .then((res) => {
                  this.update()
                })
            } else {
              billMgr
                .personEdit(this.id, item.bonusPersonId, item.adjustAmount, item.adjustReason, item.radioStr)
                .then((res) => {
                  this.update()
                })
            }
          }
          if (Number(item.adjustAmount) != 0) {
            if (!item.adjustReason || item.adjustReason.length == 0) {
              this.$refs.reason.show((reason) => {
                if (reason) {
                  item.adjustReason = reason
                } else {
                  item.adjustAmount = 0
                }
                update()
              })
              return
            }
          }
          update()
        }
        if (this.type != 'YEAR_END') {
          let Column = this.type == 'SPECIAL' ? SpecialRoomColumn : RoomColumn
          this.$refs.room.init(this, new Column(this.name, this.id, update, this.type))
          if (this.type != 'SPECIAL') {
            this.$refs.agency.init(this, new AgencyColumn(this.name, this.id, update))
          }
        }
        this.$refs.person.init(this, new PersonColumn(this.name, this.type, change))
        this.$refs.detail.init(this, new DetailColumn())
        this.update()
      },
      onTab(name) {
        this.tabName = name
        this.update()
      },
      update() {
        billMgr.detail(this.id, this.type).then((res) => {
          this.info = res
          this.agencyList = res.agentCostAdjusts
          let type = this.$dt.dictInfo().__value('bonusType', this.type) + '奖金单'
          this.title = `${res.bonusName}（${res.bonusMonth} ${type}）`
          if (this.type == 'SPECIAL') {
            this.personList = res.bonusStdDetailSpecialResp.userStimulateDetailInfos
          } else if (this.type == 'YEAR_END') {
            this.personList = res.yearUserDetailRespList
          }
          this.$refs.header.init(new BillOpt(this.info, this.name, this.type), res)
          // 若有异常，默认弹出异常提醒
          if (
            this.type != 'HANDOVER' &&
            this.type != 'YEAR_END' &&
            this.info &&
            this.info.exceptionAttach &&
            this.name == 'billEdit' &&
            this.showError
          ) {
            this.onErrExport()
            this.showError = false
          }
        })
        if (this.type != 'YEAR_END' && this.tabName == 'room') {
          this.$refs.room.fetch()
        }
        if (this.tabName == 'person') {
          this.$refs.person.fetch()
        }
        if (this.tabName == 'detail') {
          this.$refs.detail.fetch()
        }
      },
      onFetchPerson(data) {
        return billMgr.personList(this.id, this.type)
      },
      onFetchDetail(data) {
        return billMgr.radioDetail(this.id)
      },
      onFetchRoom(data) {
        if (this.type == 'SPECIAL') {
          return specialMgr.roomList(this.id, data)
        } else {
          return billMgr.roomList(this.id, this.type, data).then((res) => {
            this.roomTotal = res.total
            return res
          })
        }
      },
      onErrExport() {
        this.$Modal.confirm({
          title: '异常提醒',
          content: `当前共${this.info.exceptionNum}条订单无匹配奖金方案/职级点数<br>请查看异常信息并完成相应配置`,
          okText: '异常信息导出',
          onOk: () => {
            toolMgr.downloadFile(
              this.info.exceptionAttach.accessoryUrl,
              this.info.exceptionAttach.accessoryName
            )
          }
        })
      },
      onBatchUpdate() {
        this.$refs.upload.show({
          bonusId: this.id,
          bonusName: this.info.bonusName
        })
      },
      onExport() {
        if (this.type == 'SPECIAL') {
          return specialMgr.exportInfo(this.id)
        } else if (this.type == 'YEAR_END') {
          return yearMgr.exportInfo(this.id)
        } else {
          return billMgr.exportInfo(this.id, this.type)
        }
      },
      onRoom(item) {
        item.bonusType = this.type
        this.$refs.roomModal.show(item)
      },
      onPerson(item) {
        this.$refs.year.show(item)
      },
      onSubmit() {
        if (this.type == 'YEAR_END') {
          this.$Modal.confirm({
            title: '所填信息是否确认无误，立即提交',
            onOk: () => {
              yearMgr.submit(this.id).then((res) => {
                this.$router.go(-1)
              })
            }
          })
        } else {
          this.$refs.submit.show(this.info)
        }
      },
      onImport() {
        this.$refs.import.show({
          bonusId: this.id
        })
      },
      onClear() {
        this.$Modal.confirm({
          title: '是否确认清空房源奖金数据？',
          onOk: () => {
            specialMgr.clear(this.id).then((res) => {
              this.update()
            })
          }
        })
      },
      onAudit() {
        billMgr.isCanApproveBonus(this.$route.query.housesId).then((res) => {
          this.$refs.audit.show({
            auditId: this.auditId,
            auditType: 3,
            businessId: this.id
          })
        })
      },
      onFlow() {
        this.$refs.process.show({
          auditType: 3,
          businessId: this.id
        })
      },
      onDelete(item) {
        this.$Modal.confirm({
          title: '是否确认删除该房源奖金数据？',
          onOk: () => {
            this.$Spin.show()
            specialMgr
              .del(item.bonusDetailId)
              .then((res) => {
                this.update()
                this.$Spin.hide()
              })
              .catch((err) => {
                this.$Spin.hide()
              })
          }
        })
      },
      onEditTitle() {
        this.$refs.title.show(this.id, this.info.bonusName, (title) => {
          let type = this.$dt.dictInfo().__value('bonusType', this.type) + '奖金单'
          this.title = `${title}（${this.info.bonusMonth} ${type}）`
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .bonus {
    padding: 20px;
  }

  .title {
    line-height: 20px;
    border-left: 3px solid #2b85e4;
    padding-left: 8px;
    margin: 10px 0;
  }

  .tip {
    color: red;
    margin-bottom: 10px;
  }

  .btn {
    Button {
      margin-left: 10px;
    }
  }
</style>
